import { defineStore } from 'pinia'
import { setStorage, getStorage, removeStorage } from '@/utils/storage'
// 数据的持久化
export const useUserStore = defineStore('user', {
  state: () => ({
    token: getStorage('token') || '',
    userId: getStorage('userId') || '',
    roles: getStorage('roles') || [],
    username: getStorage('username') || ''
  }),
  actions: {
    // 修改token
    updateToken(token) {
      //   本地存储一份
      setStorage('token', token)
      //   更新内存内的数据
      this.token = token
    },
    // 移除token ...
    logout() {
      removeStorage('token')
      removeStorage('userId')
      removeStorage('username')
      removeStorage('roles')
      this.token = ''
      this.userId = ''
      this.roles = []
      this.username = ''
    },
    // 更新用户信息
    updateInfo({ userId, roles, username }) {
      setStorage('userId', userId)
      setStorage('username', username)
      setStorage('roles', roles)
      this.userId = userId
      this.roles = roles
      this.username = username
    }
  }
})
